package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Description:  连接池工具类
 * @Author one world
 * @Date 2020/9/19 0012 11:02
 */
public class ConnUtil {
    private static InputStream in;
    private static DataSource dataSource;
    private static final Logger logger = LoggerFactory.getLogger(ConnUtil.class);

    static {
        /**
         * 加载配置文件，用阿里的工厂创建数据源
         */
        in = ConnUtil.class.getResourceAsStream("/druid.properties");
        Properties properties = new Properties();
        try {
            properties.load(in);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
           logger.error("连接工具类加载配置文件异常",e);
        } catch (Exception e) {
            logger.error("连接工具类加载配置文件异常",e);
        }
    }

    /**
     * 数据库连接的获取
     *
     * @return Connection
     */
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            logger.error("连接工具类getConnection方法异常",e);
        }
        return null;
    }

    /**
     * 数据源获取
     *
     * @return
     */
    public static DataSource getDataSource() {
        return dataSource;
    }

    /**
     * 资源关闭
     *
     * @param conn
     * @param statement
     * @param rs
     */
    public static void close(Connection conn, Statement statement, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                logger.error("连接工具类关闭结果集异常",e);
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                logger.error("连接工具类关闭statement异常",e);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                logger.error("连接工具类关闭连接异常",e);
            }
        }
    }

}
